﻿/* mvcForum
 * Copyright (C) 2010-2011 Steen F. Tøttrup
 * http://mvcforum.org/
 */

using System;
using System.ComponentModel.DataAnnotations;

namespace mvcForum.Core {

	/// <summary>
	/// This class represents a file attached to a post.
	/// </summary>
	public class Attachment {
		public Attachment() { }

		public Attachment(ForumUser author, Post post, String path, String filename, Int32 size) {
			this.Size = size;
			this.Post = post;
			this.Path = path;
			this.Filename = filename;
			this.DownloadCount = 0;
			this.Created = DateTime.UtcNow;
			this.Author = post.Author;
			this.Post = post;
		}

		private Boolean imageChecked = false;
		private Boolean image = false;
		/// <summary>
		/// A boolean indicating if this attachment is an image (png, gif, jpg).
		/// </summary>
		public virtual Boolean IsImage {
			get {
				if (!imageChecked) {
					String tempFile = this.Filename.ToLower();
					image = (tempFile.EndsWith(".png") || tempFile.EndsWith(".gif") || tempFile.EndsWith(".jpg"));
					imageChecked = true;
				}
				return image;
			}
		}

		#region Properties
		/// <summary>
		/// The Id of the attachment.
		/// </summary>
		public Int32 Id { get; set; }
		/// <summary>
		/// Name of the file.
		/// </summary>
		[StringLength(Constants.FieldLengths.AttachmentFilename)]
		[Required]
		public String Filename { get; set; }
		/// <summary>
		/// The post the file is attached to.
		/// </summary>
		[Required]
		public Int32 PostId { get; set; }
		public virtual Post Post { get; set; }
		/// <summary>
		/// The size of the file, given in bytes.
		/// </summary>
		[Required]
		public Int32 Size { get; set; }
		/// <summary>
		/// The number of times the files has been downloaded.
		/// TODO: Implement this!
		/// </summary>
		[Required]
		public Int32 DownloadCount { get; set; }
		/// <summary>
		/// The path to the file, this is relative to the root of the site.
		/// </summary>
		[StringLength(Constants.FieldLengths.AttachmentPath)]
		[Required]
		public String Path { get; set; }
		/// <summary>
		/// The user that uploaded the file.
		/// </summary>
		[Required]
		public Int32 AuthorId { get; set; }
		public virtual ForumUser Author { get; set; }
		/// <summary>
		/// A timestamp for when the file was uploaded.
		/// </summary>
		private DateTime created;
		[Required]
		public DateTime Created {
			get {
				return this.created;
			}
			set {
				this.created = value.Handle();
			}
		}
		#endregion
	}
}